package com.fkcai.hansoul.service.impl;

import com.fkcai.hansoul.model.dto.post.PostCategoryOneDto;
import com.fkcai.hansoul.model.dto.post.PostCategoryTwoDto;
import com.fkcai.hansoul.mapper.PostCategoryTwoMapper;
import com.fkcai.hansoul.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 分类服务实现类
 */
@Service
public class CategoryServiceImpl implements CategoryService {
	@Autowired
	private PostCategoryTwoMapper  postCategoryTwoMapper;
	
	@Override
	@Transactional(readOnly = true)
	public List<PostCategoryOneDto> getAllCategoriesOne () {
		List<PostCategoryTwoDto> allCategories = postCategoryTwoMapper.selectAllPostCategoriesTwo();
		
		// 按一级分类名称分组
		Map<String, List<PostCategoryTwoDto>> grouped = allCategories.stream()
				.collect(Collectors.groupingBy(PostCategoryTwoDto::getParentCategoryName));
		
		// 转换为树形结构
		return grouped.entrySet().stream()
				.map(entry -> new PostCategoryOneDto(entry.getKey(), entry.getValue()))
				.collect(Collectors.toList());
	}
	
	@Override
	@Transactional(readOnly = true)
	public List<PostCategoryTwoDto> getAllPostCategoriesTwo () {
		return postCategoryTwoMapper.selectAllPostCategoriesTwo();
	}
}
